#include "login.h"
#include "ui_login.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QDebug>
#include <QCoreApplication>
#include <QDir>
Login::Login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);
    keyboard_ui = new keyboard(this);
    ui->lineEdit_2->installEventFilter(this);
    keyboard_ui->hide();
    // 初始化数据库连接
    initDatabase();
    // 在main函数中添加
    // 从数据库加载账号到ComboBox
    loadUsernamesToComboBox();
    connect(keyboard_ui, &keyboard::numberPressed, this, [=](int number) {
        ui->lineEdit_2->setText(ui->lineEdit_2->text() + QString::number(number));
    });
    connect(keyboard_ui, &keyboard::emit_clear, this, [=]() {
        ui->lineEdit_2->clear();
    });
    connect(keyboard_ui, &keyboard::emit_close, this, [=]() {
        ui->lineEdit_2->clear();
        keyboard_ui->hide();
    });
}
bool Login::eventFilter(QObject *obj, QEvent *event) {
    if (obj == ui->lineEdit_2 && event->type() == QEvent::FocusIn) {
        // 确保 keyboard_ui 已正确初始化
        if (keyboard_ui) {
            // keyboardWindow->move(0, 920);
            keyboard_ui->show();
        }
        return true; // 事件已处理
    }

    // 其他事件传递给基类处理
    return QObject::eventFilter(obj, event);
}

void Login::initDatabase()
{
    // 添加SQLite数据库驱动
    QSqlDatabase db;

    db = QSqlDatabase::addDatabase("QSQLITE", "loginConnection");

    QString appDir = QCoreApplication::applicationDirPath();
    QDir::setCurrent(appDir);  // 设置工作目录为程序所在目录

    // 然后可以用相对路径
    QString dbPath = "user_table.db";  // 相对于可执行文件目录
    // 设置数据库文件路径（根据实际路径修改）
    db.setDatabaseName(dbPath);

    // 打开数据库
    if (!db.open()) {
        QMessageBox::critical(this, "数据库错误",
                             "无法打开数据库: " + db.lastError().text());
        return;
    }
}

// 从数据库加载账号到ComboBox
void Login::loadUsernamesToComboBox()
{
    // 获取数据库连接
    QSqlDatabase db = QSqlDatabase::database("loginConnection");
    if (!db.isOpen()) {
        QMessageBox::critical(this, "数据库错误", "数据库连接已关闭");
        return;
    }

    // 执行查询
    QSqlQuery query(db);
    if (!query.exec("SELECT username FROM user")) {
        QMessageBox::critical(this, "查询错误",
                             "查询账号失败: " + query.lastError().text());
        return;
    }

    // 清空现有内容
    ui->comboBox->clear();

    // 将查询结果添加到ComboBox
    while (query.next()) {
        QString username = query.value(0).toString();
        ui->comboBox->addItem(username);

    }
}
Login::~Login()
{
    delete ui;
}


void Login::on_pushButton_clicked()
{
    // 获取输入
    QString username = ui->comboBox->currentText();
    QString inputPassword = ui->lineEdit_2->text();
     // 注意拼写，与之前代码一致
    // 验证输入
    if(username.isEmpty()) {
        QMessageBox::warning(this, "错误", "请选择用户名");
        return;
    }

    if(inputPassword.isEmpty()) {
        QMessageBox::warning(this, "错误", "请输入密码");
        return;
    }

    // 获取数据库连接
    QSqlDatabase db = QSqlDatabase::database("loginConnection");


    // 执行查询
    QSqlQuery query(db);

    QString sql = QString("SELECT password FROM user WHERE username = '%1'").arg(username);
     //这样也可以但是下面的方法可以防止ｓｑｌ注入
    query.prepare("SELECT password FROM user WHERE username = :username");
    query.bindValue(":username", username);

    if(!query.exec()) {
        QMessageBox::critical(this, "数据库错误",
                            "查询失败: " + query.lastError().text());
        return;
    }

    // 处理结果
    if(query.next()) {
        QString dbPassword = query.value(0).toString();


        if(inputPassword == dbPassword) {
            emit LoginSeccess(); // 注意拼写，与之前代码一致
        } else {
            QMessageBox::warning(this, "错误", "密码不正确");
        }
    } else {
        QMessageBox::warning(this, "错误", "用户名不存在");
    }

}
